package com.mysafe.provision.util.persistence;

import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class EntityManagerLocator {
	public static final Integer APPLICATION_ENTITY_MANAGER_ID = -1;
	private EntityManagerFactory emf;
	private Map<Integer, EntityManager> mapEntityManager;

	public EntityManagerLocator(EntityManagerFactory emf) {
		this.emf = emf;
		this.mapEntityManager = new HashMap<Integer, EntityManager>();
		this.mapEntityManager.put(APPLICATION_ENTITY_MANAGER_ID, emf.createEntityManager());
	}

	public EntityManager get(Integer idUser) {
		EntityManager em = (EntityManager) this.mapEntityManager.get(idUser);
		if (em == null) {
			em = this.emf.createEntityManager();
			put(idUser, em);
		}
		return em;
	}

	public void put(Integer id, EntityManager em) {
		this.mapEntityManager.put(id, em);
	}
}